package pf

import (
	. "chess_platform/internal/common"
	"chess_platform/internal/login"
	"chess_platform/models/client"
	"chess_platform/models/partner"
	"fmt"
	"time"
)

//[partner]渠道相关(不需要token)
type PlaceController struct {
	BaseController
}

//[partner]展示代理与玩家关系
type PartnerController struct {
	GrantController
}

/*
	1. 提供给渠道专有下载APP的二维码,每个新用户通过此二维码下载，那么用户与渠道绑定了关系
	2. 当新用户已经在A渠道下载过,再去B渠道下载,那么用户仍然是与A渠道绑定的关系
	3. 老用户再从渠道商里下载APP,不会绑定关系
*/

func (b *PlaceController) URLMapping() {
	b.Mapping("AgentLogin", b.AgentLogin)
	b.Mapping("PlayerLogin", b.PlayerLogin)
}

func (b *PartnerController) URLMapping() {
	b.Mapping("ListAgentPlayer", b.ListAgentPlayer)
}

// @Title 获取某个具体的代理的玩家
// @Description 获取某个具体的代理的玩家
// @Param   page_size    body   int     true       "每页显示数量"
// @Param   page_index   body   int     true       "第几页"
// @Success 0 {object} []订单记录
// @router /list-agent-player [post]
func (b *PartnerController) ListAgentPlayer() {
	type Params struct {
		ListParams
	}
	var p Params
	if !b.DecodeParams(&p) {
		return
	}
	if !b.ValidParams(&p) {
		return
	}
	ap, count, err := partner.ListAgentPlayerRelation(p.ListParams, b.Uid)
	if err != nil {
		LogPF.Error(b.DatabaseError(err.Error()))
		return
	}
	b.Res.Data = ap
	b.Res.Count = count
	b.ResponseSuccess()
}

// @Title 根据code获取union_id绑定用户与渠道(代理)的关系
// @Description 根据code获取union_id绑定用户与渠道(代理)的关系
// @Param   code            body    string  true      "微信用户code"
// @Param   agent_uid       body    int     true      "渠道(代理)的uid"
// @Success 0 {string} token
// @Failure 400
// @Failure 404
// @router /agent-login [post]
func (b *PlaceController) AgentLogin() {
	type Params struct {
		Code     string `json:"code" valid:"Required"`
		AgentUid int64  `json:"agent_uid" valid:"Required"`
	}
	var p Params
	if !b.DecodeParams(&p) {
		return
	}
	if !b.VerifyParamsError() {
		return
	}
	field := []string{"group_id", "root_id"}
	agentInfo, err := partner.SpecifyUserInfoById(p.AgentUid, field)
	if err != nil {
		LogPF.Error(b.DatabaseError(err.Error()))
		return
	}
	if agentInfo == nil {
		b.ResponseFail("代理不存在,请联系代理提供正确的下载地址")
		return
	}

	t, err := login.GetWeChatOpenIdAccessToken2(p.Code)
	if err != nil {
		LogPF.Error(b.SystemError(err.Error()))
		return
	}
	if t.AccessToken == "" || t.OpenId == "" {
		LogPF.Error(b.SystemError(fmt.Sprintf("无效的open_id:%v\naccess_token:%v\n", t.OpenId, t.AccessToken)))
		return
	}
	weChat, err := login.GetWeChatUserInfo(t.AccessToken, t.OpenId)
	if err != nil {
		LogPF.Error(b.SystemError(err.Error()))
		return
	}
	if weChat == nil || weChat.UnionID == "" {
		b.Res.Code = ErrNotFound
		b.Res.Msg = MsgErrUserNotFound
		b.Response()
		return
	}
	//根据union_id获取玩家信息
	pa, err := client.PassportInfoByUnionId(weChat.UnionID)
	if err != nil {
		LogPF.Error(b.DatabaseError(err.Error()))
		return
	}
	//用户已注册,不能与渠道绑定关系
	if pa != nil {
		b.ResponseSuccess("用户已注册,不能与渠道绑定关系")
		return
	}
	//用户未注册,再查找是否已经绑定了渠道了
	ap, err := partner.AgentPlayerByUnionId(weChat.UnionID)
	if err != nil {
		LogPF.Error(b.DatabaseError(err.Error()))
		return
	}

	if ap.Id == 0 { //说明从未与任何渠道绑定关系
		data := map[string]interface{}{
			"group_id":      agentInfo.GroupId, //合伙人的id
			"root_id":       agentInfo.RootId,  //总代的id
			"agent_uid":     p.AgentUid,
			"player_uid":    0,
			"union_id":      weChat.UnionID,
			"download_time": time.Now().Unix(),
		}
		partner.NewAgentPlayerRelation(data)
	} else { //已经绑定过了，更新为新的agent_uid
		data := map[string]interface{}{
			"group_id":      agentInfo.GroupId,
			"root_id":       agentInfo.RootId,
			"agent_uid":     p.AgentUid,
			"player_uid":    0,
			"union_id":      weChat.UnionID,
			"download_time": time.Now().Unix(),
		}
		partner.UpdateAgentPlayerRelation(data, ap.Id)
	}
	b.ResponseSuccess()
}

// @Title 根据code获取union_id绑定用户与用户的关系
// @Description 根据code获取union_id绑定用户与用户的关系
// @Param   code            body    string  true      "微信用户code"
// @Param   agent_uid       body    int     true      "用户的uid,只是为了方便起名为agent_uid"
// @Success 0 {string} token
// @Failure 400
// @Failure 404
// @router /player-login [post]
func (b *PlaceController) PlayerLogin() {
	type Params struct {
		Code     string `json:"code" valid:"Required"`
		AgentUid int64  `json:"agent_uid" valid:"Required"`
	}
	var p Params
	if !b.DecodeParams(&p) {
		return
	}
	if !b.VerifyParamsError() {
		return
	}

	t, err := login.GetWeChatOpenIdAccessToken2(p.Code)
	if err != nil {
		LogPF.Error(b.SystemError(err.Error()))
		return
	}
	if t.AccessToken == "" || t.OpenId == "" {
		LogPF.Error(b.SystemError(fmt.Sprintf("无效的open_id:%v\naccess_token:%v\n", t.OpenId, t.AccessToken)))
		return
	}
	weChat, err := login.GetWeChatUserInfo(t.AccessToken, t.OpenId)
	if err != nil {
		LogPF.Error(b.SystemError(err.Error()))
		return
	}
	if weChat == nil || weChat.UnionID == "" {
		b.Res.Code = ErrNotFound
		b.Res.Msg = MsgErrUserNotFound
		b.Response()
		return
	}
	//根据union_id获取玩家信息
	pa, err := client.PassportInfoByUnionId(weChat.UnionID)
	if err != nil {
		LogPF.Error(b.DatabaseError(err.Error()))
		return
	}
	//用户已注册,不能与其它用户绑定关系
	if pa != nil {
		b.ResponseSuccess("用户已注册,不能与其它用户绑定关系")
		return
	}
	//用户未注册,再查找是否已经绑定了渠道了
	ap, err := partner.AgentPlayerByUnionId(weChat.UnionID)
	if err != nil {
		LogPF.Error(b.DatabaseError(err.Error()))
		return
	}
	if ap.Id == 0 { //说明从未与任何渠道绑定关系
		data := map[string]interface{}{
			"agent_uid":     p.AgentUid,
			"player_uid":    0,
			"union_id":      weChat.UnionID,
			"download_time": time.Now().Unix(),
		}
		partner.NewAgentPlayerRelation(data)
	} else { //已经绑定过了，更新为新的agent_uid
		data := map[string]interface{}{
			"agent_uid":     p.AgentUid,
			"player_uid":    0,
			"union_id":      weChat.UnionID,
			"download_time": time.Now().Unix(),
		}
		partner.UpdateAgentPlayerRelation(data, ap.Id)
	}
	b.ResponseSuccess()
}
